package com.github.slowrookie.helper;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import com.github.slowrookie.persistence.TreePersistable;

/**
 * 生成树模型帮助类
 * 
 * @author 刘佳兴
 *
 * @param <T>
 */
public class TreeHelper<T extends TreePersistable> {
	
	public static final String hiberarchySeparator = ".";

	private final List<T> data;
	
	private T root;

	public TreeHelper(List<T> data) {
		super();
		this.data = data;
	}
	
	private Map<String, T> list2Map(){
		Map<String, T> treeMap = new HashMap<>(); 
		Iterator<T> iteratorData = data.iterator();
		while( iteratorData.hasNext() ){
			T persistable = iteratorData.next();
			if(null == root || root.getHiberarchy().length() > persistable.getHiberarchy().length()){
				root = persistable;
			}
			treeMap.put(persistable.getCode(), persistable);
		}
		return treeMap;
	}
	
	public T generateTee() { 
		Map<String, T> treeMap = list2Map(); 
		Iterator<T> iteratorMap = treeMap.values().iterator();
		while( iteratorMap.hasNext() ){
			T persistable = iteratorMap.next();
			String[] hiberarchies = persistable.getHiberarchy().split("\\" + hiberarchySeparator);
			if(hiberarchies.length < 2){
				continue;
			}
			T parent = treeMap.get(hiberarchies[hiberarchies.length -2]);
			parent.setLeaf(false);
			if(null == persistable.getLeaf()) persistable.setLeaf(true);
			parent.getChildren().add(persistable);
		}
		return root; 
	}
	
}
